<?php
require_once ('..'.DIRECTORY_SEPARATOR.'initialize.php');
//GET Request
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    include_once(Utils::getPath(array('shared', 'template.php')));
    include_once(Utils::getPath(array('repositories', 'solutionRepository.php')));
    include_once(Utils::getPath(array('repositories', 'challengeRepository.php')));
    $template = new Template('application');
    $template->initialize();

    
    if (isset($_GET['id'])){
        $chaRep = new ChallengeRepository();
        $challenge = $chaRep->getById($_GET['id']);
    }
    if(!isset($challenge)){
        Utils::goToErrorPage(StatusCodes::HTTP_BAD_REQUEST);
    }

    if (isset($_SESSION['oldform'])) {
        $oldform = $_SESSION['oldform'];
        unset($_SESSION['oldform']);
    }
    $title = 'Solution to '.$challenge->getTitle();
    ?>
    <script type="text/javascript" src="<?php echo Utils::getUrl('scripts/solution.js') ?>"></script>
    
    <h2><?php echo $title; ?></h2>

    <form id="form-solution" action="new.php" method="post" enctype="multipart/form-data" onsubmit="return validateSolutionNewForm(this);" >
        <div><input name="challenge" type="hidden" value="<?php echo $challenge->getId(); ?>" /></div>

        <div class="form-element">
            <label for="solution">Solution</label>
            <textarea name="solution" id="solution" rows="8" cols="64" onkeypress="return imposeMaxLength(this, 512);" onfocus="fieldHighlight(this, false)" ><?php if (isset($oldform['solution'])) echo $oldform['solution']; ?></textarea>
        </div>
        
        <div class="form-element">
            <label for="description">Description</label>
            <textarea name="description" id="description" rows="8" cols="64" onkeypress="return imposeMaxLength(this, 512);" onfocus="fieldHighlight(this, false)" ><?php if (isset($oldform['description'])) echo $oldform['description']; ?></textarea>
        </div>

        <div class="form-element">
            <label for="file">File (only <?php echo $strExtensions; ?> are accepted)</label>
            <input type="file" id="file" name="file"/>
            <input type="hidden" name="extensions" value="<?php echo $strExtensions ?>"/>
        </div>

        <div class="form-element">
            <input type="submit" value="Submit"/>
        </div>

    </form>
    <?php
    $template->createPage($title);
}
//POST Request
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include_once(Utils::getPath(array('repositories', 'solutionRepository.php')));
    include_once(Utils::getPath(array('repositories', 'challengeRepository.php')));

    foreach ($_POST as $key => $value) {
        $_SESSION['oldform'][$key] = $value;
    }
    
    $challengeId = $_POST['challenge'];
    $description = htmlspecialchars($_POST['description']);
    $solutionKey = $_POST['solution'];

    $errorList = array();

    if (empty($solutionKey)) {
        $errorList[] = 'Empty solution';
    } else if (strlen($solutionKey) > 512) {
        $errorList[] = 'The maximum size of the solution is 512 characters';
    }
    if (empty($description)) {
        $errorList[] = 'Empty description';
    } else if (strlen($description) > 512) {
        $errorList[] = 'The maximum size of the description is 512 characters';
    }
    
    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
        $name_file = $_FILES['file']['name'];
        $type_file = $_FILES['file']['type'];
        $size_file = $_FILES['file']['size']; //bytes
        $exte_file = end(explode(".", $name_file));
        $max_size = 5; //MB
        $accepted = in_array($exte_file, $extensions);
        if (!$accepted) {
            $errorList[] = "Only $strExtensions file extensions are accepted for upload";
        }
        if ($size_file > ($max_size * 1048576)) {//1048576 = 1024 * 1024
            $errorList[] = "File must be under $max_size MB in size";
        }
    }

    //Check if challenge exists
    $chaRep = new ChallengeRepository();
    if (isset($challengeId)){
        $chaRep = new ChallengeRepository();
        $challenge = $chaRep->getById(intval($challengeId));
    }
    if(!isset($challenge)){
        Utils::goToErrorPage();
    }
    
    //Check if solution is valid
    if($challenge->getSolutionKey() != md5($solutionKey)){
        $errorList[] = 'The solution isn\'t valid';
    }
    
    //Check for errors
    if ($errorList) {
        Utils::showErrorList($errorList);
        header("Location: new.php?id=".$challenge->getId());
        exit();
    }
    
    //Everything is ok, so we can update database
    //Update database
    $solRep = new SolutionRepository();
    $newSol = new Solution();

    $newSol->setIdChallenge($challenge->getId());
    $newSol->setIdAuthor($_SESSION['authenticatedId']);
    $newSol->setDescription($description);
    if($challenge->getIdAuthor() == $_SESSION['authenticatedId'])
        $newSol->setValid(true);
    else
        $newSol->setValid(null);
    $newSol->setQuality(1);

    $newSol = $solRep->persist($newSol);


    if (isset($_FILES['file']) && !empty($_FILES['file']['name'])) {
        $cleanName = str_replace(chr(0), '', $_FILES['file']['name']); //Anti null-byte hack
        $src = '..'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'challenges'.DIRECTORY_SEPARATOR.$newSol->getId();
        mkdir($src, 0644,true);
        $srcdir = $src;
        $src .= DIRECTORY_SEPARATOR . $cleanName;
        $urlPath = '/uploads/challenges/'.$newSol->getId().'/'.$cleanName;
        if (!move_uploaded_file($_FILES['file']['tmp_name'], $src)) {
            $solRep->remove($newSol);
            rmdir($srcdir);
            Utils::showError('An error occurred uploading your file, please try again in a moment.');
            header("Location: new.php");
            exit();
        }
        else{
            $newSol->setFilePath($urlPath);
            $newSol = $solRep->persist($newSol);
        }
    }

    unset($_SESSION['oldform']);

    Utils::showInfo('Success!');
    header('Location: '.Utils::getUrl('solution/view.php?id='.$newSol->getId()));
    exit();
}
?>
